package com.ra.service.impl;

import com.ra.config.properties.MinioProperties;
import com.ra.exception.BizException;
import com.ra.service.UploadService;
import com.ra.utils.FileUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * Author : 今晚几点睡_Ada
 * Date: 2023/3/13
 * Time: 15:22
 * 注:
 */
@Service
@SuppressWarnings("all")
public class MinioUploadServiceImpl implements UploadService {

    @Autowired
    private MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file, String path) {
        try {
            String md5 = FileUtil.getMd5(file.getInputStream());
            String extName = FileUtil.getExtName(file.getOriginalFilename());
            String fileName = md5 + extName;
            if (!exists(path + fileName)) {
                upload(path, fileName, file.getInputStream());
            }
            return getFileAccessUrl(path+ fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("文件上传失败");
        }

    }


    @SneakyThrows
    @Override
    public String uploadFile(String fileName, InputStream inputStream, String path) {
        try {
            upload(path, fileName, inputStream);
            return getFileAccessUrl(path + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("文件上传失败");
        }
    }


    //是否存在
    public Boolean exists(String filePath) {
        boolean exist = true;
        try {
            getMinioClient()
                    .statObject(StatObjectArgs.builder().bucket(minioProperties.getBucketName()).object(filePath).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }




    @SneakyThrows
    //上传
    public void upload(String path, String fileName, InputStream inputStream) {
       // System.out.println("getMinioClient() = " + getMinioClient());

        getMinioClient().putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(path + fileName).stream(
                        inputStream, inputStream.available(), -1)
                        .build());
    }


    //文件附件url
    public String getFileAccessUrl(String filePath) {
        return minioProperties.getUrl() + filePath;
    }

    //获取连接
    private MinioClient getMinioClient() {
        return MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
    }
}
